#!/bin/bash
# DJVU_Monochromator_1.sh ( 3 ) : This script , by Frank Trampe , extracts the color representation of each page in a djvu file , employs a threshold reduction to monochrome , and makes a new DjVu file .
# This script takes up to six arguments : the file that needs to be converted , the destination file , the starting page , the ending page , and the word keep if one wishes to keep the temporary page files or any other word otherwise .
# If only the file is specified , the script processes each page in the specified file . In absence of a specifying argument , the starting page is assumed to be the first page , the ending page is assumed to be the last , and all of the temporary files are deleted .

Page_Count_1=`djvudump $1 | awk '{ count = 0 } /pages/ { for(i=2;i<=NF;i++){ if($i ~ "pages"){b=i-1; print $b}}}'` ;
if [ $3 ] ; then
Start1=$3 ;
else
Start1=1 ;
fi
if [ $4 ] ; then
End1=$4 ;
else
End1=$Page_Count_1 ;
fi 
for PNum1 in `seq $Start1 $End1` ; do
ddjvu -mode=color -format=tiff -page=$PNum1 $1 Page_`Number_Crop_1 4 $PNum1`.tiff ;
tifftopnm Page_`Number_Crop_1 4 $PNum1`.tiff | ppmtopgm | pgmtopbm -threshold > Temp_1 ;
cjb2 -dpi 600 Temp_1 Page_`Number_Crop_1 4 $PNum1`.djvu ;
rm Page_`Number_Crop_1 4 $PNum1`.tiff Temp_1 ;
done
if [ $2 ] ; then
djvm -c $2 Page_*.djvu
fi
if [ $4 = "save" ] ; then
echo 'Page_*.djvu' ;
else
rm ./Page_*.djvu ;
fi

